﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CompanyBussiness;

namespace Website.admin.Control
{
    public partial class cProductList : System.Web.UI.UserControl
    {
        ProductManagement proMana = new ProductManagement();
        LanguagesManagement languageMana = new LanguagesManagement();
        CompanyBussiness.Product pro = new Product();
        CheckValid cv = new CheckValid();
        public int CurPage = 1;
        int TotalRow;
        int TotalPage;
        int StartRow = 0;
        int typeProductIDs;

        protected void Page_Load(object sender, EventArgs e)
        {
            fail.Visible = false;
            success.Visible = false;
            //bindDropDownListFromDateTime(ddlFromHour, "h", false);
            //bindDropDownListFromDateTime(ddlFromMinute, "m", false);
            //BindDropDownListToDateTime(ddlToHour, "h", true);
            //BindDropDownListToDateTime(ddlToMinute, "m", true);
            //bdFromDate.SelectedDate = DateTime.Now;
            //bdToDate.SelectedValue = DateTime.Now;

            if (!Page.IsPostBack)
            {
                if (Request[CONST.QUERYSTRING_TYPE_PRODUCT] == null)
                {
                    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "TypeProduct";
                    Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=TypeProduct&Mod=" + "MPRODUCT");
                }
                else
                {
                    typeProductIDs = int.Parse(Request[CONST.QUERYSTRING_TYPE_PRODUCT].ToString());
                    lbListName.Text = proMana.GetTypeProductByID(typeProductIDs).TypeProductName.ToString();
                    ContentSearch();
                }
            }
            
        }

        protected int GetRowinPage()
        {
            return int.Parse(dropRows.SelectedValue.ToString());
        }

        protected void LoadGridView(Product pro, int take)
        {
            try
            {
                if (Request["Page"] == null)
                {
                    CurPage = 1;
                }
                else
                {
                    CurPage = Convert.ToInt32(Request["Page"]);
                }

                dropChoicePage.SelectedValue = CurPage.ToString();

                if (CurPage > 1)
                {
                    StartRow = (CurPage - 1) * 10;
                }
                else
                {
                    StartRow = 0;
                }

                GridViewProductList.DataSource = proMana.GetProductSearchNotDate(pro, take, StartRow);
                GridViewProductList.DataBind();
                TotalRow = proMana.GetNumberProductSearchNotDate(pro);
                if (TotalRow == 0)
                {
                    pnPagination.Visible = false;
                    fail.Visible = true;
                    btnSave.Visible = false;
                    btnCancel.Visible = false;
                    lbError.Text = "Không có sản phẩm nào!";
                    return;
                }
                else
                {
                    pnPagination.Visible = true;
                    conditionsRight.Visible = true;
                    fail.Visible = false;
                    success.Visible = false;
                    btnSave.Visible = true;
                    btnCancel.Visible = true;
                }

                this.Pagination(take);
            }
            catch (Exception)
            {

            }
        }

        protected void Pagination(int take)
        {
            try
            {
                if (TotalRow % take == 0)
                    TotalPage = TotalRow / take;
                else
                    TotalPage = (TotalRow / take) + 1;

                dropChoicePage.Items.Clear();
                for (int i = 0; i < TotalPage; i++)
                {
                    dropChoicePage.Items.Add((i + 1).ToString());
                }


                if (CurPage > 1)
                {
                    lnkFirst.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=ListNews&" + CONST.QUERYSTRING_CATEGORY + "=" + typeProductIDs + "&Page=" + Convert.ToString(1);
                    lnkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=ListNews&" + CONST.QUERYSTRING_CATEGORY + "=" + typeProductIDs + "&Page=" + Convert.ToString(CurPage - 1);
                }
                if (CurPage < TotalPage && CurPage > 1)
                {
                    lnkLast.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=ListNews&" + CONST.QUERYSTRING_CATEGORY + "=" + typeProductIDs + "&Page=" + Convert.ToString(TotalPage.ToString());
                    lnkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=ListNews&" + CONST.QUERYSTRING_CATEGORY + "=" + typeProductIDs + "&Page=" + Convert.ToString(CurPage + 1);
                }


                numCurrent.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=ListNews&" + CONST.QUERYSTRING_CATEGORY + "=" + typeProductIDs + "&Page=" + Convert.ToString(CurPage);
                numBefore.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=ListNews&" + CONST.QUERYSTRING_CATEGORY + "=" + typeProductIDs + "&Page=" + Convert.ToString(CurPage - 1);
                numAfter.NavigateUrl = Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=ListNews&" + CONST.QUERYSTRING_CATEGORY + "=" + typeProductIDs + "&Page=" + Convert.ToString(CurPage + 1);

                if (CurPage == 1 && TotalPage == 1)
                {
                    numCurrent.Text = CurPage.ToString();
                    numBefore.Text = "";
                    numAfter.Text = "";
                    numBefore.Visible = false;
                    numAfter.Visible = false;
                }
                else if (CurPage == 1 && TotalPage > 1)
                {
                    numCurrent.Text = CurPage.ToString();
                    numBefore.Text = "";
                    numBefore.Visible = false;
                    numAfter.Text = Convert.ToString(CurPage + 1);
                }
                else if (1 < CurPage && CurPage < TotalPage)
                {
                    numCurrent.Text = CurPage.ToString();
                    numBefore.Text = Convert.ToString(CurPage - 1);
                    numAfter.Text = Convert.ToString(CurPage + 1);
                }
                else if (CurPage == TotalPage)
                {
                    numCurrent.Text = CurPage.ToString();
                    numBefore.Text = Convert.ToString(CurPage - 1);
                    numAfter.Text = "";
                    numAfter.Visible = false;
                }
            }
            catch (Exception)
            {

            }
        }

        protected void dropChoicePage_SelectedIndexChanged(object sender, EventArgs e)
        {
            CurPage = Convert.ToInt32(dropChoicePage.SelectedValue.ToString());
            Response.Redirect(Request.CurrentExecutionFilePath + "?" + CONST.ACTION + "=TypeProductDetail&" + CONST.QUERYSTRING_TYPE_PRODUCT + "=" + typeProductIDs + "&Page=" + Convert.ToString(CurPage) + "&Mod=MPRODUCT");
        }

        protected void dropRows_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ContentSearch();
            }
            catch (Exception)
            {

            }        
        }

        protected void ContentSearch()
        {
            typeProductIDs = int.Parse(Request[CONST.QUERYSTRING_TYPE_PRODUCT].ToString());

             string error = string.Empty;

             //if (CheckValidDate(ref error))
             //{
                 pro.TypeProductID = typeProductIDs;

                 pro.ProductName = txtSearch.Text;

                 if (dropStatus.SelectedValue.ToString() == "true")
                 {
                     pro.ProductStatus = true;
                 }
                 else if (dropStatus.SelectedValue.ToString() == "false")
                 {
                     pro.ProductStatus = false;
                 }

                 pro.ProductCode = txtProductCode.Text;

                 this.LoadGridView(pro, int.Parse(dropRows.SelectedValue.ToString()));
             //}
             //else
             //{
             //    lbError.Text = error;
             //    fail.Visible = true;
             //    return;
             //}
           
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                ContentSearch(); 
            }
            catch (Exception)
            {

            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            btnCancel.Enabled = false;
            StartRow = CurPage * 10;
            for (int i = 0; i < GridViewProductList.Rows.Count; i++)
            {
                pro = proMana.GetProductByID(int.Parse(GridViewProductList.DataKeys[i].Value.ToString()));
                bool status = ((CheckBox)GridViewProductList.Rows[i].FindControl("checkStatus")).Checked;
                proMana.UpdateProduct((int)pro.ProductID, pro.ProductName, pro.ProductDes, pro.ProductAuthor, pro.ProductSkin,(int)pro.ProductQuantity, (float)pro.ProductPrice,(DateTime)pro.ProductDateIn,pro.ProductImg,status,(bool)pro.ImagesStatus,(int)pro.TypeProductID,pro.FileAttach,pro.Features);
            }
            ContentSearch();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                ContentSearch();
            }
            catch (Exception)
            {

            }        
        }

        protected void btnEdit_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "EditProduct")
            {
                Session[CONST.SESSION_PRODUCT_ID] = Convert.ToInt32(e.CommandArgument);
                try
                {
                    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "CreateProduct";
                    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_TYPE] = "UpdateProduct";
                    Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=CreateProduct&" + CONST.SESSION_PRODUCT_ID + "=" + int.Parse(Session[CONST.SESSION_PRODUCT_ID].ToString()) + "&Mod=MPRODUCT");
                }
                catch (Exception)
                {

                }
            }
        }

        private static void bindDropDownListFromDateTime(DropDownList ddlControl, string option, bool getNow)
        {
            switch (option)
            {
                case "h":
                    {
                        var li1 = new ListItem("Giờ", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        for (int i = 0; i <= 23; i++)
                        {
                            var li = new ListItem(i.ToString(), i.ToString());
                            ddlControl.Items.Add(li);
                        }
                        if (getNow)
                        {
                            ddlControl.SelectedValue = DateTime.Now.Hour.ToString();
                        }
                        else
                        {
                            ddlControl.SelectedIndex = 1;
                        }
                        break;
                    }
                case "m":
                    {
                        var li1 = new ListItem("Phút", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        for (int i = 0; i <= 59; i++)
                        {
                            var li = new ListItem(i.ToString(), i.ToString());
                            ddlControl.Items.Add(li);
                        }
                        if (getNow)
                        {
                            ddlControl.SelectedValue = DateTime.Now.Minute.ToString();
                        }
                        else
                        {
                            ddlControl.SelectedIndex = 1;
                        }
                        break;
                    }
                default:
                    {
                        var li1 = new ListItem("Chọn", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        ddlControl.SelectedIndex = 0;
                        break;
                    }
            }
        }

        private static void BindDropDownListToDateTime(ListControl ddlControl, string option, bool getNow)
        {
            switch (option)
            {
                case "h":
                    {
                        var li1 = new ListItem("Giờ", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        for (int i = 0; i <= 23; i++)
                        {
                            var li = new ListItem(i.ToString(), i.ToString());
                            ddlControl.Items.Add(li);
                        }
                        if (getNow)
                        {
                            ddlControl.SelectedValue = DateTime.Now.Hour.ToString();
                        }
                        else
                        {
                            ddlControl.SelectedIndex = 0;
                        }
                        break;
                    }
                case "m":
                    {
                        var li1 = new ListItem("Phút", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        for (int i = 0; i <= 59; i++)
                        {
                            var li = new ListItem(i.ToString(), i.ToString());
                            ddlControl.Items.Add(li);
                        }
                        if (getNow)
                        {
                            ddlControl.SelectedValue = DateTime.Now.Minute.ToString();
                        }
                        else
                        {
                            ddlControl.SelectedIndex = 0;
                        }
                        break;
                    }
                default:
                    {
                        var li1 = new ListItem("Chọn", string.Empty);
                        ddlControl.Items.Insert(0, li1);
                        ddlControl.SelectedIndex = 0;
                        break;
                    }
            }
        }

        protected void GridViewProductList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.DataRow) return;


            CompanyBussiness.Product obj = (CompanyBussiness.Product)e.Row.DataItem;

            Label lbDes = (Label)e.Row.FindControl("lbDes");
            
            if (obj.ProductDes == null)
            {
                lbDes.Text = "";
                
            }
            else if (obj.ProductDes.Length >= 200)
            {
                lbDes.Text = obj.ProductDes.Substring(0,200)+"...";
               
            }
            else if (obj.ProductDes.Length < 200)
            {
                lbDes.Text = obj.ProductDes;
               
            }
            
        }

        //private DateTime GetFromDate()
        //{
        //    string time = ddlFromHour.SelectedValue + ":" + ddlFromMinute.SelectedValue + ":00";
        //    string date = bdFromDate.SelectedDate.ToShortDateString();
        //    DateTime result = DateTime.Parse(date + " " + time);
        //    return result;
        //}

        //private DateTime GetToDate()
        //{
        //    string time = ddlToHour.SelectedValue + ":" + ddlToMinute.SelectedValue + ":00";
        //    string date = bdToDate.SelectedDate.ToShortDateString();
        //    DateTime result = DateTime.Parse(date + " " + time);
        //    return result;
        //}

        //private bool CheckValidDate(ref string error)
        //{
        //    error = string.Empty;
        //    if (ddlFromHour.SelectedValue == string.Empty)
        //    {
        //        error += "<li>Bạn chưa chọn giờ ngày bắt đầu</li>";
        //    }
        //    if (ddlFromMinute.SelectedValue == string.Empty)
        //    {
        //        error += "<li>Bạn chưa chọn phút cho ngày bắt đầu</li>";
        //    }
        //    if (ddlToHour.SelectedValue == string.Empty)
        //    {
        //        error += "<li>Bạn chưa chọn giờ ngày kết thúc</li>";
        //    }
        //    if (ddlToMinute.SelectedValue == string.Empty)
        //    {
        //        error += "<li>Bạn chưa chọn phút cho ngày kết thúc</li>";
        //    }
        //    if (bdFromDate.SelectedValue == null)
        //    {
        //        error += "<li>Bạn chưa chọn ngày bắt đầu</li>";
        //    }
        //    if (bdToDate.SelectedValue == null)
        //    {
        //        error += "<li>Bạn chưa chọn ngày kết thúc</li>";
        //    }
        //    if (!error.Equals(string.Empty))
        //    {
        //        return false;
        //    }
        //    DateTime fromDate = GetFromDate();
        //    DateTime toDate = GetToDate();

        //    if (fromDate > toDate)
        //    {
        //        error = "Khoảng thời gian bạn chọn không hợp lệ";
        //        return false;
        //    }
        //    return true;
        //}

    }
}